const {Router} = require("express");
const responseResult = require("../../../util/responseResult");
const path = require("path");
const fs = require("fs");
const multer = require("multer");
const {getNextId, getTime, checkParam} = require("../../../util");
const cryptoJs = require("crypto-js");
const {uploalSql} = require("../../../model/commonModel");

const paths = {
    upload: "/", read_file: "/:name"
}
const uploadRouter = Router();

// 上传文件父目录设置
const dir = path.dirname(path.dirname(path.dirname(__dirname)));
// 文件存储目录
const uploadDir = path.join(dir, "upload");

// 判断路径是否存在
if (!fs.existsSync(uploadDir)) {
    // 创建
    fs.mkdirSync(uploadDir)
}

// 过滤文件
const fileFilter = (req, file, cb) => {
    // 支持上传图片、pdf、.xls
    if (file.mimetype.startsWith('image/') || file.mimetype.startsWith('application/pdf') || file.mimetype.startsWith('application/vnd.ms-excel')) {
        return cb(null, true);
    }
    return cb(responseResult.error(`不支持上传${file.mimetype}文件`), true)
}

// 随机生成文件名
const setFileName = (originalname) => {
    const timeJab = getTime();
    const randomPart = cryptoJs.lib.WordArray.random(8).toString();
    const extension = path.extname(originalname);
    return timeJab + '_' + randomPart + extension;
}

// 不单独配置文件名字，会存在文件没有后缀情况
const storage = multer.diskStorage({
    destination(req, file, cb) {
        cb(null, uploadDir)
    }, filename(req, file, cb) {
        cb(null, setFileName(file.originalname))
    },
})

// 上传文件处理事件
const upload = multer({
    dest: uploadDir, fileFilter, storage, limits: {
        fileSize: 3 * 1024 * 1024
    },
}).single("file");

// 上传文件路由处理函数
const uploadHandle = (req, res, cb) => {
    upload(req, res, err => {
        if (err) {
            if (err.code === 'LIMIT_FILE_SIZE') {
                return res.json(responseResult.error("上传的文件大小不能超出3M"))
            }
            delete err.storageErrors
            return res.json(err);
        }
        if (!req.file) {
            return res.json(responseResult.error("请选择上传文件"));
        }
        const data = {
            path: req.protocol + '://' + req.get('host') + '/api/common/upload/' + req.file.filename,
            size: req.file.size,
            id: getNextId(),
            type: req.file.mimetype,
            create_time: getTime()
        };
        cb(data);
    })
}
/**
 * @swagger
 * /common/upload:
 *   post:
 *     tags:
 *       - 公共接口
 *     summary: 上传文件
 *     description: 文件大小限制为3m，仅支持音视频、图片、xls以及pdf文件
 *     consumes: multipart/form-data
 *     parameters:
 *       - in: formData
 *         name: file
 *         type: file
 *         required: true
 *     responses:
 *       200:
 *         description: 上传成功
 *         schema:
 *           type: object
 *           properties:
 *             code:
 *               type: number
 *               title: 状态值 0或1
 *             message:
 *                 type: string
 *             data:
 *               type: object
 *               properties:
 *                 path:
 *                   type: string
 *                   title: 路径
 *                 size:
 *                   type: number
 *                   title: 文件大小
 *                 id:
 *                   type: string
 *                   title: key
 *                 type:
 *                   type: string
 *                   title: 文件类型
 *                 create_time:
 *                   type: string
 *                   title: 创建时间
 */

uploadRouter.post(paths.upload, (req, res) => {
    uploadHandle(req, res, data => {
        // 插入数据
        uploalSql(data, () => {
            return res.json(responseResult.success("上传成功", data))
        }, res)
    });
});

// 读取文件
uploadRouter.get(paths.read_file, (req, res) => {
    const {name} = req.params;
    // 获取当前文件所在路径
    let dirPath = path.join(`${__dirname}+../../../../upload/${name}`);
    dirPath = path.normalize(dirPath);
    fs.readFile(dirPath, (err, data) => {
        if (err) {
            res.writeHead(404, {"Content-Type": "text/plain;charset=utf-8"});
            return res.end("文件不存在")
        }
        res.end(data);
    })
})


module.exports = uploadRouter;
